package com.jjh.jhwebserver.handler;

import com.jjh.jhwebserver.context.*;
import com.jjh.jhwebserver.mapper.UrlMappingHandler;
import com.jjh.jhwebserver.core.ServletContext;

import java.io.*;
import java.net.Socket;

/**
 * 该类实现了Runnable接口
 * 处理socket请求
 * @author JJH
 */
public class JhRequestHandler implements Runnable{


    private Socket socket =null;

    private ServletContext context;

    public JhRequestHandler(Socket socket,ServletContext context){
        this.context = context;
        this.socket = socket;
    }


    @Override
    public void run() {

        try {
            //获取输入流
            InputStream in = socket.getInputStream();
            OutputStream os = socket.getOutputStream();

            //1.创建俩对象
            HttpServletRequest requset = new HttpServletRequest(in);
            HttpServletResponse response = new HttpServletResponse();


            //2.路径映射
            UrlMappingHandler urlMappingHandler =
                    new UrlMappingHandler(requset,response,context);
            Object result = urlMappingHandler.urlMapping(requset,response,context);
            //处理找不到的情况
            if(result==null){
                response.setStatus(404);
            }else {
                //静态文本资源
                if(result.getClass()==String.class){
                    response.setStatus(200);
                    response.write(result.toString());
                }else if(result.getClass()==File.class){
                    response.setStatus(200);
                    response.write((File) result);
                }
                else{
                    //servlet动态资源
                    HttpServlet servlet = (HttpServlet) result;
                    servlet.service(requset,response);
                    response.setStatus(200);

                }
            }


            //3。对响应在封装
             new JhResponseHandler(response,os);

            //关闭流
            os.flush();
            os.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                //最终一定要确保socket关闭
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }
}
